package com.controller;

import com.Security.encodeUtil;
import com.pojo.user;
import com.service.userService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.service.userService;


public class loginServlet extends HttpServlet {

    private com.service.userService userService=new userService();


    /**
     * 登录校验
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String id = req.getParameter("userid");
        String cd = req.getParameter("checkcode"); //输入的验证码
        if(cd==null||cd.equals("")){
            resp.sendRedirect("login.jsp");
            return;
        }
        String checkcode = cd.toUpperCase(); //转换
        if(id==null||id.equals("")){
            resp.sendRedirect("login.jsp");
            return;
        }
        try{
            int userid = Integer.parseInt(id);
        }catch (Exception e){
            resp.sendRedirect("login.jsp");
            return;
        }

        String psd = req.getParameter("password");
        String password = encodeUtil.encode(psd);

        if(password==null||password.equals("")){
            resp.sendRedirect("login.jsp");
            return;
        }
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        if(code==null||code.equals("")){
            resp.sendRedirect("login.jsp");
            return;
        }
        if(!encodeUtil.encode(checkcode).equals(code)){
            resp.sendRedirect("login.jsp");
            return;
        }
        int userid = Integer.parseInt(id);
        try {
            ResultSet resultSet = userService.checkUser(userid, password);
            while (resultSet.next()){
                if(resultSet.getInt(1)==userid&&resultSet.getString(3).equals(password)){
                     Cookie cookie=new Cookie("loginUser",userid+"");
                     cookie.setMaxAge(60*60*24*7); //设置7天过期
                     resp.addCookie(cookie);
                    req.getRequestDispatcher("dump.jsp").forward(req,resp);
                    break;
                }
            }



        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        resp.sendRedirect("login.jsp");


    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
